<template>
    <div class="login-container">
        <div class="taiji-container">
            <div class="taiji"></div>
        </div>
        <div class="form-box">
            <!-- 登录表单 -->
            <div class="login-box" v-if="!showRegister && !showUpdatePassword">
                <h2 class="login-title">寻经问道</h2>
                <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" label-position="top">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="loginForm.phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号"
                            class="custom-input" />
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" placeholder="请输入密码"
                            show-password class="custom-input" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
                            <i class="yin-yang-icon"></i> 登 录
                        </el-button>
                    </el-form-item>
                    <div class="toggle-text">
                        未有账号？<span @click="toggleForm">立即注册</span><span @click="toggleFormUpdate"
                            style="padding-left: 10px;">忘记密码</span>
                    </div>
                </el-form>
            </div>

            <!-- 注册表单 -->
            <div class="register-box" v-if="showRegister">
                <h2 class="login-title">注册</h2>
                <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="login-form"
                    label-position="top">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="registerForm.phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号"
                            class="custom-input" />
                    </el-form-item>

                    <el-form-item label="验证码" prop="captcha">
                        <div class="code-input">
                            <el-input v-model="registerForm.captcha" placeholder="请输入验证码" class="custom-input" />
                            <el-button class="code-btn" :disabled="codeDisabled" @click="getVerifyCode">
                                {{ codeText }}
                            </el-button>
                        </div>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input v-model="registerForm.password" prefix-icon="el-icon-lock" placeholder="请设置密码(6-16位)"
                            show-password class="custom-input" />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="passwordTwo">
                        <el-input v-model="registerForm.passwordTwo" prefix-icon="el-icon-lock" placeholder="请再次输入密码"
                            show-password class="custom-input" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" class="login-btn" @click="handleRegister" :loading="regLoading">
                            <i class="yin-yang-icon"></i> 注 册
                        </el-button>
                    </el-form-item>
                    <div class="toggle-text">
                        已有账号？<span @click="toggleForm">立即登录</span>
                    </div>
                </el-form>
            </div>


            <div class="register-box" v-if="showUpdatePassword">
                <h2 class="login-title">修改密码</h2>
                <el-form ref="updatePassword" :model="updatePassword" :rules="updatePasswordRules" class="login-form"
                    label-position="top">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="updatePassword.phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号"
                            class="custom-input" />
                    </el-form-item>

                    <el-form-item label="验证码" prop="captcha">
                        <div class="code-input">
                            <el-input v-model="updatePassword.captcha" placeholder="请输入验证码" class="custom-input" />
                            <el-button class="code-btn" :disabled="codeDisabled" @click="getVerifyCode1">
                                {{ codeText }}
                            </el-button>
                        </div>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input v-model="updatePassword.password" prefix-icon="el-icon-lock"
                            placeholder="请设置密码(6-16位)" show-password class="custom-input" />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="passwordTwo">
                        <el-input v-model="updatePassword.passwordTwo" prefix-icon="el-icon-lock" placeholder="请再次输入密码"
                            show-password class="custom-input" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" class="login-btn" @click="handleRegisterUpdate">
                            <i class="yin-yang-icon"></i> 确 定
                        </el-button>
                    </el-form-item>
                    <div class="toggle-text">
                        已有账号？<span @click="toggleFormUpdate">立即登录</span>
                    </div>
                </el-form>
            </div>

        </div>
        <div class="gua-container">
            <div v-for="gua in guaList" class="gua" :style="{ transform: `rotate(${gua.rotate}deg)` }">{{
                gua.text }}</div>
        </div>
    </div>
</template>

<script>
import { login, register, getSmsCaptcha, resetPassword } from '@/api/index'
export default {
    data() {
        // 手机号验证
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号'))
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error('手机号格式不正确'))
            } else {
                callback()
            }
        }

        // 密码验证
        const validatePassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入密码'))
            } else if (value.length < 6 || value.length > 16) {
                callback(new Error('密码长度需在6-16位之间'))
            } else {
                callback()
            }
        }

        // 确认密码验证
        const validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.registerForm.password) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        }
        const validateConfirmPassword2 = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.updatePassword.password) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        }

        return {
            showRegister: false,
            // 登录表单数据
            loginForm: {
                phone: '',
                password: ''
            },
            showUpdatePassword: false,
            loginRules: {
                phone: [{ validator: validatePhone, trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
            },
            loading: false,
            // 注册表单数据
            registerForm: {

                phone: '',
                password: '',
                passwordTwo: '',
                captcha: '',
            },
            updatePassword: {

                phone: '',
                password: '',
                passwordTwo: '',
                captcha: '',
            },
            registerRules: {
                phone: [{ validator: validatePhone, trigger: 'blur' }],
                captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
                password: [{ validator: validatePassword, trigger: 'blur' }],
                passwordTwo: [{ validator: validateConfirmPassword, trigger: 'blur' }]
            },
            updatePasswordRules: {
                phone: [{ validator: validatePhone, trigger: 'blur' }],
                captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
                password: [{ validator: validatePassword, trigger: 'blur' }],
                passwordTwo: [{ validator: validateConfirmPassword2, trigger: 'blur' }]
            },
            regLoading: false,
            // 验证码相关
            codeText: '获取验证码',
            codeDisabled: false,
            countdown: 60,
            timer: null,
            // 八卦元素
            guaList: [
                { text: '䷀', rotate: 0 }, // 乾
                { text: '䷁', rotate: 45 }, // 坤
                { text: '䷂', rotate: 90 }, // 屯
                { text: '䷃', rotate: 135 } // 蒙
            ]
        }
    },
    methods: {
        // 切换登录/注册表单
        toggleForm() {
            this.showRegister = !this.showRegister;
            clearInterval(this.timer)
            this.$nextTick(() => {
                if (this.showRegister) {
                    this.$refs.loginForm && this.$refs.loginForm.clearValidate()
                } else {
                    this.$refs.registerForm && this.$refs.registerForm.clearValidate()
                }
            })
        },

        toggleFormUpdate() {
            clearInterval(this.timer)
            this.showUpdatePassword = !this.showUpdatePassword
            this.$nextTick(() => {
                if (this.showRegister) {
                    this.$refs.loginForm && this.$refs.loginForm.clearValidate()
                } else {
                    this.$refs.updatePassword && this.$refs.updatePassword.clearValidate()
                }
            })
        },

        // 登录逻辑
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    login(this.loginForm)
                        .then((res) => {
                            if (res.code == 200) {

                                // 存储
                                res.data.user['nickName'] = '游客';
                                res.data.user['avatarUrl'] = 'https://www.xjwd.net:9500/file/statics/2025/01/03/11_20250103075128A010.png';

                                localStorage.setItem('token', res.data.token);
                                localStorage.setItem('userInfo', JSON.stringify(res.data.user));
                                // 登录成功跳转首页
                                this.$router.push('/')
                                this.loading = false
                            } else {
                                this.$message.error(res.msg);
                                this.loading = false
                            }
                        })
                        .catch((error) => {
                            console.log('错误内容:', error);

                        });
                }
            })
        },

        // 注册逻辑
        handleRegister() {
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.regLoading = true;
                    register(this.registerForm).then((res) => {
                        if (res.code == 200) {
                            this.regLoading = false
                            this.$message.success('注册成功')
                            clearInterval(this.timer)
                            this.toggleForm()
                        } else {
                            this.regLoading = false
                            this.$message.error(res.msg);
                        }
                    });

                }
            })
        },
        handleRegisterUpdate() {
            this.$refs.updatePassword.validate(valid => {
                if (valid) {
                    resetPassword(this.updatePassword).then((res) => {
                        console.log(res);
                        if (res.code == 200) {

                            this.$message.success('修改成功')
                            clearInterval(this.timer)
                            this.toggleFormUpdate()
                        } else {

                            this.$message.error(res.msg);
                        }
                    });
                }
            })
        },
        // 获取验证码
        getVerifyCode() {
            this.$refs.registerForm.validateField('phone', (error) => {
                if (!error) {
                    // 模拟发送验证码
                    getSmsCaptcha({ phone: this.registerForm.phone }).then((res) => {
                        if (res.code == 200) {

                            // 这里此提示会被start()方法中的提示覆盖
                            this.$message.success('验证码已发送');
                            this.startCountdown()
                        } else {
                            this.$message.success(res.data.msg);
                        }
                    })


                } else {
                    this.$message.error('请先输入正确的手机号')
                }
            })
        },

        getVerifyCode1() {
            this.$refs.updatePassword.validateField('phone', (error) => {
                if (!error) {
                    // 模拟发送验证码
                    getSmsCaptcha({ phone: this.updatePassword.phone }).then((res) => {
                        if (res.code == 200) {

                            // 这里此提示会被start()方法中的提示覆盖
                            this.$message.success('验证码已发送');
                            this.startCountdown()
                        } else {
                            this.$message.success(res.msg);
                        }
                    })


                } else {
                    this.$message.error('请先输入正确的手机号')
                }
            })
        },
        // 开始倒计时
        startCountdown() {
            this.codeDisabled = true
            this.codeText = `${this.countdown}秒后重新获取`
            this.timer = setInterval(() => {
                this.countdown--
                this.codeText = `${this.countdown}秒后重新获取`
                if (this.countdown <= 0) {
                    clearInterval(this.timer)
                    this.codeDisabled = false
                    this.codeText = '获取验证码'
                    this.countdown = 60
                }
            }, 1000)
        }
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}
</script>

<style scoped lang="scss">
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #2a1f1d url('data:image/svg+xml,<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><path fill="%239C928C" d="M20 100Q40 50 100 20q60 30 80 80t-80 80q-60-30-80-80Z"/></svg>');
    position: relative;
    overflow: hidden;
}

.form-box {
    position: relative;
    z-index: 2;
    width: 531px;
}

.taiji-container {
    position: absolute;
    width: 400px;
    height: 400px;
    animation: rotate 20s linear infinite;

    .taiji {
        width: 100%;
        height: 100%;
        background: linear-gradient(to right, #000 50%, #fff 50%);
        border-radius: 50%;
        position: relative;

        &::before,
        &::after {
            content: '';
            position: absolute;
            width: 50%;
            height: 50%;
            border-radius: 50%;
            border: 20px solid #2a1f1d;
        }

        &::before {
            background: #fff;
            left: 25%;
            transform: translateY(-50%);
        }

        &::after {
            background: #000;
            left: 25%;
            bottom: 0;
            transform: translateY(50%);
        }
    }
}

.login-box,
.register-box {
    width: 100%;
    padding: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
    border: 1px solid #c4a484;
    transition: all 0.5s ease;
}

.login-title {
    text-align: center;
    color: #6b4f4b;
    font-size: 28px;
    margin-bottom: 30px;
    font-family: '楷体', cursive;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.login-btn {
    width: 100%;
    background: linear-gradient(45deg, #6b4f4b, #c4a484);
    border: none;
    font-size: 18px;
    color: #fff;
    height: 45px;
    transition: all 0.3s;
    position: relative;

    &:hover {
        background: linear-gradient(45deg, #c4a484, #6b4f4b);
        transform: scale(1.02);
    }
}

.yin-yang-icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    background: linear-gradient(to right, #000 50%, #fff 50%);
    border-radius: 50%;
    margin-right: 8px;
}

.gua-container {
    position: absolute;
    width: 100%;
    height: 100%;
    pointer-events: none;

    .gua {
        position: absolute;
        font-size: 24px;
        color: rgba(156, 146, 140, 0.3);
        font-family: 'SimSun';

        &:nth-child(1) {
            top: 10%;
            left: 10%;
        }

        &:nth-child(2) {
            top: 10%;
            right: 10%;
        }

        &:nth-child(3) {
            bottom: 10%;
            left: 10%;
        }

        &:nth-child(4) {
            bottom: 10%;
            right: 10%;
        }
    }
}

::v-deep .custom-input {
    .el-input__inner {
        background: rgba(255, 255, 255, 0.9);
        border: 1px solid #c4a484;
        border-radius: 20px;
        height: 40px;

        &:focus {
            border-color: #6b4f4b;
            box-shadow: 0 0 8px rgba(107, 79, 75, 0.3);
        }
    }
}

.code-input {
    display: flex;

    .el-input {
        flex: 1;
        margin-right: 10px;
    }

    .code-btn {
        width: 120px;
        background: linear-gradient(45deg, #8d6e63, #a1887f);
        border: none;
        color: #fff;

        &:disabled {
            background: #d7ccc8;
        }
    }
}

.toggle-text {
    text-align: center;
    color: #6b4f4b;
    margin-top: 15px;

    span {
        color: #8d6e63;
        cursor: pointer;
        text-decoration: underline;

        &:hover {
            color: #6b4f4b;
        }
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>